package com.vf.admin.utils;

import com.vf.admin.common.Constants;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 上传文件处理工具
 */
public class UploadFileUtils {
    public static UploadFileUtils getInstance(){
        return new UploadFileUtils();
    }

    /**
     *  MultipartFile类型转为普通File文件
     */
    public String convert(MultipartFile multipartFile,String filePath){
        try{
            if (multipartFile.isEmpty()) {
                return null;
            }

            String fileName = multipartFile.getOriginalFilename();  // 文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
            fileName = UUID.randomUUID() + suffixName; // 新文件名

            String filePathName = filePath + fileName;
            File dest = new File(Constants.PATH_OS_BASE + filePathName);
            if(!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                multipartFile.transferTo(dest);
            } catch (IOException e) {
                return null;
            }
            if(dest==null && dest.length()<=0){
                return null;
            }
            return filePathName;
        }catch(Exception e){
            return null;
        }
    }

}
